function getCookie(url) {
    try {
        let cookieManager = android.webkit.CookieManager.getInstance();
        return cookieManager.getCookie(url) || '';
    } catch (e) {
        console.trace('获取cookie异常', e);
        return '';
    }
}

function getForJson(url) {
    try {
        let options = {
            method: 'GET',
            headers: {
                'Cookie': getCookie(url)
            }
        };
        let response = http.request(url, options);
        if (response.statusCode <200 || response.statusCode > 299) {
            console.log(response)
            throw new Error(response.statusCode + ": " + response.body.string());
        }
        return response.body.json();
    } catch (e) {
        console.trace(e);
        return {};
    }

}

function postForJson(url, data) {
    try {
        let options = {
            method: 'POST',
            body: data || '',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'Cookie': getCookie(url)
            }
        };
        let response = http.request(url, options);
        if (response.statusCode <200 || response.statusCode > 299) {
            console.log(response)
            throw new Error(response.statusCode + ": " + response.body.string());
        }
        return response.body.json();
    } catch (e) {
        console.trace(e);
        return {};
    }
}

/** 定时领水滴 */
function getWater() {
    let url = "https://api.m.jd.com/client.action?functionId=gotThreeMealForFarm&body=%7B%22type%22%3A0%2C%22version%22%3A4%2C%22channel%22%3A1%7D&appid=wh5";
    let response = getForJson(url);
    // console.log(JSON.stringify(response));
    if (response.code == 0) {
        console.log('定时领水滴：获得%s滴', response.amount);
    } else {
        console.log('定时领水滴失败: ' + JSON.stringify(response));
    }
}

/** 水滴雨 */
function initTask() {
    let url = "https://api.m.jd.com/client.action";
    let data = 'functionId=taskInitForFarm&body={"version":3}&appid=wh5';
    let response = postForJson(url, data);
    console.log(JSON.stringify(response));
    if (response.code == 0) {
        console.log('水滴雨：获得%s滴', response.addEnergy);
    } else {
        console.log('水滴雨领取失败: ' + JSON.stringify(response));
    }

}


/** 水滴雨 */
function warterRain() {
    let url = "https://api.m.jd.com/client.action";
    let data = 'functionId=waterRainForFarm&body={"type":1,"hongBaoTimes":41,"version":3}&appid=wh5';
    let response = postForJson(url, data);
    // console.log(JSON.stringify(response));
    if (response.code == 0) {
        console.log('水滴雨：获得%s滴', response.addEnergy);
    } else {
        console.log('水滴雨领取失败: ' + JSON.stringify(response));
    }

}
function main() {
    getWater();
    // initTask();
    warterRain();
}
main();